package com.navi.entity;

import com.navi.job.service.MainCallable;
import com.navi.util.LogUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;

import javax.swing.text.StyledEditorKit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import static com.navi.constant.GenericDef.*;

/**
 * Created by ghost on 2018/12/8.
 */
@Slf4j
public class ThreadUtil {

//    @Value("${thread_pool_count}")
//    private Integer threadPoolCnt;


    public static Integer getThreadResult(String type, List<MainCallable> mainCallableListCommon) throws Exception {
        // 创建一个线程池
        ExecutorService pool = Executors.newFixedThreadPool(3);
        List<Future<Integer>> futureTaskList=new ArrayList<>();
        try{
            mainCallableListCommon.forEach(thread->futureTaskList.add(pool.submit(thread)));
        }catch (Exception e){
            throw e;
        }finally {
            // 关闭线程池
            pool.shutdown();
        }


        //获取结果
        try {
            int res=RETURN_SUCCESS;
            for (Future obj : futureTaskList) {
                // 从Future对象上获取任务的返回值
                if (RETURN_FAISE==((Integer) obj.get())) {
                    return RETURN_FAISE;
                } else if(RETURN_REWORK_ALLCASE==((Integer) obj.get())){
                    res=RETURN_REWORK_ALLCASE;
                }
            }
            return res;
        } catch (Exception e) {
            throw new Exception(type+"多线程 执行失败！失败原因："+ LogUtil.stackTraceToString(e));
        }
    }
}
